package walletadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strconv"

	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/logx"
)

type QueryCurrencyExchangeConfigListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryCurrencyExchangeConfigListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryCurrencyExchangeConfigListLogic {
	return &QueryCurrencyExchangeConfigListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理后台查询钱包币种兑换配置列表
func (l *QueryCurrencyExchangeConfigListLogic) QueryCurrencyExchangeConfigList(in *pb.QueryCurrencyExchangeConfigListReq) (*pb.QueryCurrencyExchangeConfigListResp, error) {
	defer utils.RecoverPanic()

	var err error
	var list []*wallet.CurrencyExchangeConfig
	list, err = l.svcCtx.CurrencyExchangeConfigModel.Find(l.ctx, 0, in.PayChannelId, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var rsp pb.QueryCurrencyExchangeConfigListResp
	rsp.List = make([]*pb.CurrencyExchangeConfig, 0)
	if len(list) <= 0 {
		return &rsp, nil
	}

	if in.PageNo <= 1 {
		rsp.Total, err = l.svcCtx.CurrencyExchangeConfigModel.Count(l.ctx, 0)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	for i := 0; i < len(list); i++ {
		vl := pb.CurrencyExchangeConfig{
			Id:             list[i].Id,
			State:          list[i].State,
			MoneyType:      list[i].MoneyType,
			CurrencyType:   list[i].CurrencyType,
			CreateTime:     list[i].CreateTime.Format(dbkey.DateTimeCNFormat),
			UpdateTime:     list[i].UpdateTime.Format(dbkey.DateTimeCNFormat),
			MoneyIcon:      list[i].MoneyIcon,
			CurrencyIcon:   list[i].CurrencyIcon,
			MoneyName:      list[i].MoneyName,
			CurrencyName:   list[i].CurrencyName,
			PayChannelId:   list[i].PayChannelId,
			ConfigName:     list[i].ConfigName,
			ServiceFeeRate: decimal.NewFromInt(list[i].ServiceFeeRate).Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2),
		}

		vl.CurrencyAmount = strconv.FormatInt(list[i].CurrencyAmount, 10)
		vl.MoneyAmount = strconv.FormatInt(list[i].MoneyAmount, 10)
		rsp.List = append(rsp.List, &vl)
	}

	return &rsp, nil
}
